<template>
	<div>
		<CommonSearch v-model="tableConfig.searchParams" :config="searchConfig"></CommonSearch>
		<CommonTable :config="tableConfig" ref="commonTable">
			<template #status="{ row }">
				<el-tooltip :content="`状态:${row.status == 1 ? '启用' : '禁用'}`" placement="top">
					<el-switch
						@click="handlerStatus(row)"
						:value="row.status"
						active-color="#13ce66"
						inactive-color="#dcdfe6"
						active-value="1"
						inactive-value="0"
					></el-switch>
				</el-tooltip>
			</template>
		</CommonTable>
		<DialogForm :config="formConfig" v-model="formConfig.modelData" ref="dialogForm">
			<template #menuIds>
				<el-form-item label="菜单权限:">
					<el-checkbox-group v-model="menuIdTypes">
						<el-checkbox label="1">全选/全不全</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label=".">
					<el-tree
						class="tree-class"
						node-key="menuId"
						ref="tree"
						highlight-current
						show-checkbox
						:data="menus"
						:props="{
							children: 'children',
							label: 'menuName',
						}"
					></el-tree>
				</el-form-item>
			</template>
		</DialogForm>
	</div>
</template>

<script lang="javascript">
	import {
		reactive,
		toRefs,
		onMounted,
		getCurrentInstance,
		watch,
		nextTick
	} from 'vue';
	import { CREATE, UPDATE, DELETE, QUERY, IMPORT } from '@/utils/Const';
	import { listToMenu } from '@/utils/Tools';

	import {
		getRoleListApi,
		createRoleApi,
		updateRoleApi,
		deleteRoleApi,
		getMenuListApi
	} from '@/api/system.api';
	import { noNumberToNull } from '@/utils/validate';
	export default {
		name : 'Role',
		setup () {
			let Instance = getCurrentInstance().proxy;
			let commonTable = null;
			let dialogForm = null;
			let tree = null;
			let data = reactive({
				menus : [],
				menuIdTypes : ['0'],
				searchConfig : {
					handlerSearch () {
						return commonTable.fetchData({ isResetPageNumber : true });
					},
					form : [
						{
							type : 'text',
							label : '角色名称:',
							placeholder : '请输入角色名称',
							key : 'roleName'
						},
						{
							type : 'text',
							label : '权限字符:',
							placeholder : '请输入权限字符',
							key : 'roleKey'
						},
						{
							type : 'select',
							label : '状态:',
							placeholder : '请选择状态',
							key : 'status',
							options : [
								{
									value : '',
									label : '全部'
								},
								{
									value : '1',
									label : '正常'
								},
								{
									value : '0',
									label : '停用'
								}
							]
						},
						{
							type : 'daterange',
							commentsName : 'datePicker',
							label : '创建时间:',
							placeholder : '请选择创建时间',
							key : 'params'
						}
					]
				},
				tableConfig : {
					searchParams : {},
					reqApiMethod : getRoleListApi,
					handlerOperate : async (payload, row) => {
						data.formConfig.type = payload.butType;
						let formConfig = {
							data : Array.isArray(row) ? row[0] : '',
							...data.formConfig
						};

						let names = [];
						let ids = [];
						switch (payload.butType) {
						case CREATE:
							data.menus = await getMenus();
							data.menuIdTypes = ['0'];
							dialogForm.open(data.formConfig);
							nextTick(() => {
								tree = Instance.$refs['tree'];
							});
							break;
						case DELETE:
							row.forEach((item) => {
								names.push(item.roleName);
								ids.push(item.roleId);
							});
							Instance.$hyConfirm({
								subTitle : `是否确定删除【${names.join()}】`,
								callback : async (done) => {
									await deleteRoleApi({ ids : ids.join() });
									done();
									commonTable.fetchData();
								}
							});
							break;
						case UPDATE:
							data.menus = await getMenus();
							data.menuIdTypes = ['0'];
							dialogForm.open(formConfig);
							nextTick(() => {
								tree = Instance.$refs['tree'];
								let checkMenuId = [];
								row[0].menuIds &&
	                  row[0].menuIds.forEach((menuId) => {
	                  	checkMenuId.push({
	                  		menuId
	                  	});
	                  });
								tree.setCheckedNodes(checkMenuId);
							});
							break;
						case QUERY:
							formConfig.disabled = true;
							data.menus = await getMenus();
							data.menuIdTypes = ['0'];
							dialogForm.open(formConfig);
							nextTick(() => {
								tree = Instance.$refs['tree'];
								let checkMenuId = [];
								row[0].menuIds &&
	                  row[0].menuIds.forEach((menuId) => {
	                  	checkMenuId.push({
	                  		menuId
	                  	});
	                  });
								tree.setCheckedNodes(checkMenuId);
							});
							break;
						}
					},
					mergeTable : () => {},
					columns : [
						{
							type : 'index'
						},
						{
							type : 'selection'
						},
						{
							title : '角色编号',
							field : 'roleId'
						},
						{
							title : '角色名称',
							field : 'roleName'
						},
						{
							title : '权限字符',
							field : 'roleKey'
						},
						{
							title : '排序',
							field : 'roleSort'
						},
						{
							title : '状态',
							field : 'status',
							formatter : (value) => {
								if (Number(value) === 0) {
									return '停用';
								}
								return '正常';
							}
						},
						{
							title : '操作时间',
							field : 'createTime'
						}
					],
					globalOperate : [
						{
							butType : CREATE,
							name : '新增',
							color : 'primary',
							role : [],
							icon : 'el-icon-plus'
						},
						{
							butType : DELETE,
							name : '删除',
							enable : '2',
							color : 'danger',
							role : [],
							icon : 'el-icon-delete'
						},
						{
							butType : UPDATE,
							name : '修改',
							enable : '1',
							color : 'success',
							role : [],
							icon : 'el-icon-edit'
						},
						{
							butType : QUERY,
							name : '查看',
							enable : '1',
							color : 'warning',
							role : [],
							icon : 'el-icon-edit'
						},
						{
							butType : IMPORT,
							name : '导入',
							color : 'el-icon-upload2',
							role : [],
							icon : 'el-icon-upload2'
						}
					],
					operate : [
						{
							butType : UPDATE,
							type : 'text',
							name : '修改',
							role : [],
							icon : 'el-icon-edit'
						},
						{
							butType : DELETE,
							type : 'text',
							name : '删除',
							role : [],
							icon : 'el-icon-delete'
						}
					]
				},
				formConfig : {
					type : '',
					async handlerSubmit (params) {
						let menuIds = [];
						tree.getCheckedNodes().forEach((item) => menuIds.push(item.menuId));
						params.menuIds = menuIds;
						switch (data.formConfig.type) {
						case CREATE:
							await createRoleApi(params);
							break;
						case UPDATE:
							await updateRoleApi(params);
							break;
						}
						return commonTable.fetchData();
					},
					form : [
						{
							type : 'text',
							label : '角色Id',
							key : 'roleId',
							hide : true
						},
						{
							type : 'text',
							label : '角色名称:',
							placeholder : '请输入角色名称',
							maxlength : 10,
							key : 'roleName',
							rules : [
								{ required : true, message : '请输入岗位名称', trigger : 'blur' }
							]
						},
						{
							type : 'text',
							label : '权限字符:',
							maxlength : 8,
							placeholder : '请输入权限字符',
							key : 'roleKey',
							rules : [
								{ required : true, message : '请输入权限字符', trigger : 'blur' }
							]
						},
						{
							type : 'text',
							label : '角色顺序:',
							placeholder : '请输入角色顺序',
							key : '角色顺序',
							maxlength : 2,
							handlerLimiting : (val) => {
								return noNumberToNull(val);
							},
							rules : [
								{ required : true, message : '请输入角色顺序', trigger : 'blur' }
							]
						},
						{
							type : 'text',
							label : '菜单权限:',
							key : 'menuIds'
						},
						{
							type : 'radio',
							label : '角色状态:',
							key : 'status',
							defaultValue : '1',
							options : [
								{
									value : '1',
									label : '正常'
								},
								{
									value : '0',
									label : '停用'
								}
							]
						},
						{
							type : 'textarea',
							label : '备注:',
							placeholder : '请输入内容',
							key : 'remark',
							maxlength : 100
						}
					]
				}
			});

			onMounted(() => {
				commonTable = Instance.$refs['commonTable'];
				dialogForm = Instance.$refs['dialogForm'];
			});

			const handlerStatus = (row) => {
				let { status, roleName } = row;
				Instance.$hyConfirm({
					subTitle : `是否${status == 0 ? '启用' : '禁用'}【${roleName}】`,
					callback : (done) => {
						done();
						row.status = !status;
						commonTable.fetchData();
					}
				});
			};

			let getMenus = async () => {
				let res = await getMenuListApi();
				let menus = listToMenu({ list : res.list, idKey : 'menuId' });
				return menus;
			};

			watch(
				() => data.menuIdTypes,
				() => {
					try {
						if (data.menuIdTypes.some((item) => item == 1)) {
							tree.setCheckedNodes(data.menus);
						} else {
							tree.setCheckedKeys([]);
						}
					} catch (e) {
						console.log(e);
					}
				}
			);

			return {
				handlerStatus,
				...toRefs(data)
			};
		}
	};
</script>

<style lang="scss" scoped>
	.tree-class {
		border: 1px solid #e5e6e7;
		border-radius: 4px;
	}
</style>
